package loggers

import (
	"io"
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

// Config 是日志相关的配置，包含滚动配置，日志级别，context keys集合
type Config struct {
	// rolling config
	FileName   string // 文件保存路径: stdout, stderr, discard或者具体的文件路径
	MaxSize    int    // 每一个日志文件最大大小： M
	MaxBackups int    // 最多备份多少日志文件
	MaxAge     int    // 文件保留天数
	Compress   bool   // 是否压缩

	// logconfig
	Level     string   // 日志级别： DEBUG, INFO, WARN, ERROR
	FieldKeys []string // 需要从 context.Context 中获取的key集合
}

func NewConfig() *Config {
	return &Config{
		FileName:   "stderr",
		MaxSize:    10,
		MaxBackups: 20,
		MaxAge:     30,
		Compress:   true,
		Level:      "INFO",
	}
}

// parseWriteSyncer parses zap level from config.
func (c *Config) parseLevel() zapcore.Level {
	switch c.Level {
	case "DEBUG":
		return zapcore.DebugLevel
	case "INFO":
		return zapcore.InfoLevel
	case "WARN":
		return zapcore.WarnLevel
	case "ERROR":
		return zapcore.ErrorLevel
	default:
		return zap.InfoLevel
	}
}

// parseWriteSyncer parses zap output from config.
func (c *Config) parseWriteSyncer() io.Writer {
	switch c.FileName {
	case "stderr":
		return os.Stderr
	case "stdout":
		return os.Stdout
	case "discard":
		return io.Discard
	default:
		return &lumberjack.Logger{
			Filename:   c.FileName,
			MaxSize:    c.MaxSize,
			MaxBackups: c.MaxBackups,
			MaxAge:     c.MaxAge,
			Compress:   c.Compress,
		}
	}
}
